import sys, os
from PyQt5.QtCore import pyqtSlot, QDir, pyqtSignal, Qt
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QFileDialog,QSlider
from PyQt5.QtGui import QImage, QPixmap
from main_form import Ui_cvcar
from setting import SettingGUI
from configobj import ConfigObj
from program_block import ProgramBlock
from camera_thread import CameraThread
from motor_test import Motor
import platform
sys.path.append(os.path.dirname(os.getcwd()))
sys.path.append(os.path.dirname(__file__))

class MainGui(QWidget):
    line_camera_close = pyqtSignal()
    od_camera_close = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_cvcar()
        self.ui.setupUi(self)
        self.ui.cb_follow_line.clicked.connect(self.cb_check_changed)
        self.ui.cb_find_intersection.clicked.connect(self.cb_check_changed)
        self.ui.cb_find_roadblock.clicked.connect(self.cb_check_changed)
        self.ui.cb_object_detection.clicked.connect(self.cb_check_changed)
        self.ui.cb_find_zebra_crossing.clicked.connect(self.cb_check_changed)
        self.ui.cb_show_available.clicked.connect(self.cb_addition_changed)
        self.ui.cb_show_render.clicked.connect(self.cb_addition_changed)
        self.ui.cb_print_frame_rate.clicked.connect(self.cb_addition_changed)
        self.ui.cb_save_video.clicked.connect(self.cb_addition_changed)
        self.ui.btn_cancel.clicked.connect(self.close)

        self.conf = ConfigObj("./setting.ini", encoding='utf8')
        self.setting_gui = SettingGUI()
        self.get_objects_setting()
        self.line_camera_thread = None
        self.od_camera_thread = None


        self.motor = Motor()
        self.ui.hs_left_speed.setTickInterval(15)
        self.ui.hs_left_speed.setTickPosition(QSlider.TicksBelow)
        self.ui.hs_right_speed.setTickInterval(15)
        self.ui.hs_right_speed.setTickPosition(QSlider.TicksBelow)
        self.ui.hs_left_speed.valueChanged.connect(self.slider_change)
        self.ui.hs_right_speed.valueChanged.connect(self.slider_change)

    def slider_change(self):
        left = self.ui.hs_left_speed.value()
        right = self.ui.hs_right_speed.value()
        self.ui.lab_left_speed.setText(str(left))
        self.ui.lab_right_speed.setText(str(right))
        self.motor.drive_motor(left, right)

    @pyqtSlot()
    def on_btn_test_motor_clicked(self):
        if self.ui.btn_test_motor.text() == "开  始":
            self.ui.btn_test_motor.setText("结   束")
            self.ui.gb_motor.setEnabled(True)
            self.slider_change()
        else:
            self.ui.btn_test_motor.setText("开  始")
            self.ui.gb_motor.setEnabled(False)
            self.motor.stop()

    @pyqtSlot()
    def on_btn_open_line_camera_clicked(self):
        if self.ui.btn_open_line_camera.text() == "打开巡线摄像头":
            self.conf.reload()
            self.ui.btn_open_line_camera.setText("关闭巡线摄像头")
            self.line_camera_thread = CameraThread(camera=self.get_platform(camera_name='line_camera'))
            self.line_camera_thread.changePixmap.connect(self.set_line_camera_image)
            self.line_camera_close.connect(self.line_camera_thread.do_stop)
            self.line_camera_thread.start()
        else:
            self.ui.btn_open_line_camera.setText("打开巡线摄像头")
            if self.line_camera_thread:
                self.line_camera_close.emit()

    @pyqtSlot()
    def on_btn_open_od_camera_clicked(self):
        if self.ui.btn_open_od_camera.text() == "打开目标检测摄像头":
            self.conf.reload()
            self.ui.btn_open_od_camera.setText("关闭目标检测摄像头")
            self.od_camera_thread = CameraThread(camera=self.get_platform(camera_name='od_camera'))
            self.od_camera_thread.changePixmap.connect(self.set_od_camera_image)
            self.od_camera_close.connect(self.od_camera_thread.do_stop)
            self.od_camera_thread.start()
        else:
            self.ui.btn_open_od_camera.setText("打开目标检测摄像头")
            if self.od_camera_thread:
                self.od_camera_close.emit()

    @pyqtSlot(QImage)
    def set_line_camera_image(self, image):
        image = image.scaled(240, 180, Qt.KeepAspectRatio)
        self.ui.lb_line_camera.setPixmap(QPixmap.fromImage(image))

    @pyqtSlot(QImage)
    def set_od_camera_image(self, image):
        image = image.scaled(240, 180, Qt.KeepAspectRatio)
        self.ui.lb_od_camera.setPixmap(QPixmap.fromImage(image))

    def get_platform(self, camera_name):
        if platform.system().lower() == 'windows':
            return int(self.conf['camera'][camera_name])
        elif platform.system().lower() == 'linux':
            return '/dev/video' + self.conf['camera'][camera_name]
        else:
            return None

    def get_objects_setting(self):
        if self.conf['objects']['follow_line'] == 'True':
            self.ui.cb_follow_line.setChecked(True)
        else:
            self.ui.cb_follow_line.setChecked(False)

        if self.conf['objects']['find_intersection'] == 'True':
            self.ui.cb_find_intersection.setChecked(True)
        else:
            self.ui.cb_find_intersection.setChecked(False)

        if self.conf['objects']['find_zebra_crossing'] == 'True':
            self.ui.cb_find_zebra_crossing.setChecked(True)
        else:
            self.ui.cb_find_zebra_crossing.setChecked(False)

        if self.conf['objects']['find_roadblock'] == 'True':
            self.ui.cb_find_roadblock.setChecked(True)
        else:
            self.ui.cb_find_roadblock.setChecked(False)

        if self.conf['objects']['object_detection'] == 'True':
            self.ui.cb_object_detection.setChecked(True)
        else:
            self.ui.cb_object_detection.setChecked(False)

        if self.conf['addition']['show_available'] == "True":
            self.ui.cb_show_available.setChecked(True)
        else:
            self.ui.cb_show_available.setChecked(False)
        if self.conf['addition']['show_render'] == "True":
            self.ui.cb_show_render.setChecked(True)
        else:
            self.ui.cb_show_render.setChecked(False)
        if self.conf['addition']['print_frame_rate'] == "True":
            self.ui.cb_print_frame_rate.setChecked(True)
        else:
            self.ui.cb_print_frame_rate.setChecked(False)
        if self.conf['addition']['save_video'] == "True":
            self.ui.cb_save_video.setChecked(True)
        else:
            self.ui.cb_save_video.setChecked(False)

    def cb_check_changed(self):

        self.conf['objects'][self.sender().objectName()[3:]] = self.sender().isChecked()
        self.conf.write()

    def cb_addition_changed(self):
        self.conf['addition'][self.sender().objectName()[3:]] = self.sender().isChecked()
        self.conf.write()

    @pyqtSlot()
    def on_btn_setting_clicked(self):
        self.setting_gui.show()

    @pyqtSlot()
    def on_btn_object_clicked(self):
        fname, ftype = QFileDialog.getSaveFileName(self, '保存模板文件', '..', "python (*.py)")
        if fname:
            pb = ProgramBlock(template_dir="gui_template.py")
            insert_text = ""
            cf = self.conf['objects']
            if self.ui.cb_follow_line.isChecked():
                insert_text += pb.e_follow_line
            if self.ui.cb_find_intersection.isChecked():
                insert_text += pb.e_find_intersection
            if self.ui.cb_find_zebra_crossing.isChecked():
                insert_text += pb.e_find_zebra_crossing
            if self.ui.cb_find_roadblock.isChecked():
                insert_text += pb.e_find_roadblock
            if self.ui.cb_object_detection.isChecked():
                insert_text += pb.e_object_detection

            pb.build_file(insert_text, save_dir=fname)

            dlgtitle = "消息框"
            strInfo = "模板文件保存成功!，是否关闭窗口？"
            defaultBtn = QMessageBox.No
            result = QMessageBox.question(self, dlgtitle, strInfo, QMessageBox.Yes | QMessageBox.No, defaultBtn)
            if result == QMessageBox.Yes:
                self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = MainGui()
    gui.show()
    sys.exit(app.exec_())